package com.jeeplus.modules.web.web;

import cn.hutool.core.lang.Dict;
import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.DataEntity;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.web.entity.YjMahjongHall;
import com.jeeplus.modules.web.entity.YjMahjongHallRoom;
import com.jeeplus.modules.web.entity.YjQrcodes;
import com.jeeplus.modules.web.service.YjMahjongHallRoomService;
import com.jeeplus.modules.web.service.YjMahjongHallService;
import com.jeeplus.modules.web.service.YjQrcodesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 棋牌室房间Controller
 * @author liangbing
 * @version 2021-03-11
 */
@Api(value = "YjMahjongHallRoomController", description = "棋牌室房间控制器")
@Controller
@RequestMapping(value = "${adminPath}/web/yjMahjongHallRoom")
public class YjMahjongHallRoomController extends BaseController {
    @Autowired
    private YjMahjongHallService yjMahjongHallService;

    @Autowired
    private YjMahjongHallRoomService yjMahjongHallRoomService;

    @Autowired
    private YjQrcodesService yjQrcodesService;

    private final String ROOM_KEY = "yjMahjongHallRoom";

    @ModelAttribute
    public YjMahjongHallRoom get(@RequestParam(required=false) String id) {
        YjMahjongHallRoom entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = yjMahjongHallRoomService.get(id);
        }
        if (entity == null){
            entity = new YjMahjongHallRoom();
        }
        return entity;
    }

    /**
     * 棋牌室房间列表页面
     */
    @RequiresPermissions("web:yjMahjongHallRoom:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/web/yjMahjongHallRoomList";
    }

    /**
     * 棋牌室房间列表数据
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallRoom:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(YjMahjongHallRoom yjMahjongHallRoom, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<YjMahjongHallRoom> page = yjMahjongHallRoomService.findPage(new Page<YjMahjongHallRoom>(request, response), yjMahjongHallRoom);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑棋牌室房间表单页面
     */
    @RequiresPermissions(value={"web:yjMahjongHallRoom:view","web:yjMahjongHallRoom:add","web:yjMahjongHallRoom:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(YjMahjongHallRoom yjMahjongHallRoom, Model model) {
        model.addAttribute("yjMahjongHallRoom", yjMahjongHallRoom);
        if(StringUtils.isBlank(yjMahjongHallRoom.getId())){//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/web/yjMahjongHallRoomForm";
    }

    /**
     * 保存棋牌室房间
     */
    @RequiresPermissions(value={"web:yjMahjongHallRoom:add","web:yjMahjongHallRoom:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(YjMahjongHallRoom yjMahjongHallRoom, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, yjMahjongHallRoom)){
            return form(yjMahjongHallRoom, model);
        }

        //检查二维码
        if (yjMahjongHallRoom.getQrcodes() != null && StringUtils.isNotBlank(yjMahjongHallRoom.getQrcodes().getQrcode())) {
            AjaxJson checkResult;

            // 新增的时候
            String roomId = yjMahjongHallRoom.getId();
            String qrcode = yjMahjongHallRoom.getQrcodes().getQrcode();

            if (StringUtils.isBlank(roomId)) {
                checkResult = checkQrcode(qrcode);
            } else {
                checkResult = checkQrcode(roomId, qrcode);
            }

            if (!checkResult.isSuccess()) {
                addMessage(model, checkResult.getMsg());
                return form(yjMahjongHallRoom, model);
            }
        }

        // 检查是否重复创建
        boolean isDuplicate = checkDuplicate(yjMahjongHallRoom);
        if (isDuplicate) {
            addMessage(model, "保存失败！房间已存在！");
            return form(yjMahjongHallRoom, model);
        }

        //新增或编辑表单保存
        yjMahjongHallRoomService.saveHallRoom(yjMahjongHallRoom);//保存
        addMessage(redirectAttributes, "保存棋牌室房间成功");
        return "redirect:"+ Global.getAdminPath()+"/web/yjMahjongHallRoom/?repage";
    }

    /**
     * 删除棋牌室房间
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallRoom:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(YjMahjongHallRoom yjMahjongHallRoom, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        yjMahjongHallRoomService.delete(yjMahjongHallRoom);
        j.setMsg("删除棋牌室房间成功");
        return j;
    }

    /**
     * 批量删除棋牌室房间
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHallRoom:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
//        for(String id : idArray){
//            yjMahjongHallRoomService.delete(yjMahjongHallRoomService.get(id));
//        }
        yjMahjongHallRoomService.batchDeleteByLogic(Arrays.asList(idArray));
        j.setMsg("删除棋牌室房间成功");
        return j;
    }

    /**
     * 微信端新建房间
     * @param yjMahjongHallRoom
     * @return
     */
    @ApiOperation(notes = "createMahjongHallRoom", httpMethod = "POST", value = "微信端新建棋牌室房间")
    @ResponseBody
    @PostMapping(value = "createMahjongHallRoom")
    public AjaxJson createMahjongHallRoom(@RequestBody YjMahjongHallRoom yjMahjongHallRoom) {
        // 检查参数
        BeanValidators.validateWithException(validator, yjMahjongHallRoom);

        AjaxJson j = new AjaxJson();

        // 特殊参数检查
        if (StringUtils.isBlank(yjMahjongHallRoom.getOpenid())) {
            j.setSuccess(false);
            j.setMsg("用户不能为空!");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallRoom.getSalesmanPhone())) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空");
            return j;
        }

        if (yjMahjongHallRoom.getMahjongHall() == null || StringUtils.isBlank(yjMahjongHallRoom.getMahjongHall().getId())) {
            j.setSuccess(false);
            j.setMsg("房间所在棋牌室不能为空！");
            return j;
        }

        // 检查棋牌室是否存在
        YjMahjongHall yjMahjongHall = yjMahjongHallService.get(yjMahjongHallRoom.getMahjongHall().getId());
        if (yjMahjongHall == null) {
            j.setSuccess(false);
            j.setMsg("房间所在棋牌室不存在！");
            return j;
        }

        // 检查是否重复创建
        boolean isDuplicate = checkDuplicate(yjMahjongHallRoom);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("房间已存在！");
            return j;
        }

        //检查二维码是否已经绑定
        if (yjMahjongHallRoom.getQrcodes() != null && StringUtils.isNotBlank(yjMahjongHallRoom.getQrcodes().getQrcode())) {
            AjaxJson checkResult = checkQrcode(yjMahjongHallRoom.getQrcodes().getQrcode());
            if (!checkResult.isSuccess()) {
                return checkResult;
            }

            LinkedHashMap<String, Object> map = checkResult.getBody();
            if (map != null && map.containsKey(ROOM_KEY)) {
                YjQrcodes yjQrcodes = new YjQrcodes((String)map.get(ROOM_KEY));
                yjMahjongHallRoom.setQrcodes(yjQrcodes);
            }
        }

        //新增或编辑表单保存
        yjMahjongHallRoom.setCreateDate(new Date());
        yjMahjongHallRoomService.saveHallRoom(yjMahjongHallRoom);//保存

        j.setSuccess(true);
        j.setMsg("棋牌室房间创建成功！");
        j.getBody().put("data", yjMahjongHallRoom);
        return j;
    }

    /**
     * 微信端获得棋牌室房间信息
     * @return
     */
    @ApiOperation(notes = "getMahjongHallRoomInfo", httpMethod = "DELETE", value = "微信端编辑棋牌室房间")
    @ResponseBody
    @GetMapping(value = "getMahjongHallRoomInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallRoomId", value = "hallRoomId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson getMahjongHallRoomInfo(@NotBlank String hallRoomId) {
        AjaxJson j = new AjaxJson();

        if (StringUtils.isBlank(hallRoomId)) {
            j.setSuccess(false);
            j.setMsg("房间id不能为空");
            return j;
        }

        YjMahjongHallRoom yjMahjongHallRoom = yjMahjongHallRoomService.get(hallRoomId);
        j.getBody().put("data", yjMahjongHallRoom);
        return j;
    }

    /**
     * 微信端修改房间
     * @param yjMahjongHallRoom 棋牌室房间信息
     * @return
     */
    @ApiOperation(notes = "editMahjongHallRoom", httpMethod = "PUT", value = "微信端修改棋牌室房间")
    @ResponseBody
    @PutMapping(value = "editMahjongHallRoom")
    public AjaxJson editMahjongHallRoom(@RequestBody YjMahjongHallRoom yjMahjongHallRoom) {
        AjaxJson j = new AjaxJson();

        // 参数检查
        if (yjMahjongHallRoom.getMahjongHall() == null || StringUtils.isBlank(yjMahjongHallRoom.getMahjongHall().getId())) {
            j.setSuccess(false);
            j.setMsg("棋牌室id不能为空");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallRoom.getId())) {
            j.setSuccess(false);
            j.setMsg("房间id不能为空");
            return j;
        }

        if (StringUtils.isBlank(yjMahjongHallRoom.getName())) {
            j.setSuccess(false);
            j.setMsg("房间名称不能为空");
            return j;
        }

        // 检查是否重复创建
        boolean isDuplicate = checkDuplicate(yjMahjongHallRoom);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("房间已存在");
            return j;
        }

        // 检查二维码是否已经创建过
        if (yjMahjongHallRoom.getQrcodes() != null && StringUtils.isNotBlank(yjMahjongHallRoom.getQrcodes().getQrcode())) {
            // 新增的时候
            String roomId = yjMahjongHallRoom.getId();
            String qrcode = yjMahjongHallRoom.getQrcodes().getQrcode();
            AjaxJson checkResult = checkQrcode(roomId, qrcode);
            if (!checkResult.isSuccess()) {
                j.setSuccess(false);
                j.setMsg(checkResult.getMsg());
                return j;
            }

            // 得到数据库中二维码信息
            LinkedHashMap<String, Object> map = checkResult.getBody();
            if (map != null && map.containsKey(ROOM_KEY)) {
                YjQrcodes yjQrcodes = new YjQrcodes((String)map.get(ROOM_KEY));
                yjMahjongHallRoom.setQrcodes(yjQrcodes);
            }
        }

        // 更新棋牌室房间信息
        yjMahjongHallRoomService.saveHallRoom(yjMahjongHallRoom);//保存

        j.setSuccess(true);
        j.setMsg("更新成功");
        return j;
    }

    /**
     * 微信端删除棋牌室房间
     * @return
     */
    @ApiOperation(notes = "deleteMahjongHallRoom", httpMethod = "DELETE", value = "微信端删除棋牌室房间")
    @ResponseBody
    @DeleteMapping(value = "deleteMahjongHallRoom")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallRoomId", value = "hallRoomId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson deleteMahjongHallRoom(@NotBlank String hallRoomId) {
        AjaxJson j = new AjaxJson();

        if (StringUtils.isBlank(hallRoomId)) {
            j.setSuccess(false);
            j.setMsg("房间id不能为空");
            return j;
        }

        // 检查房间是否已经被删除了
        YjMahjongHallRoom yjMahjongHallRoom = yjMahjongHallRoomService.get(hallRoomId);
        if (DataEntity.DEL_FLAG_DELETE.equals(yjMahjongHallRoom.getDelFlag())) {
            j.setSuccess(false);
            j.setMsg("房间已被其他人删除");
            return j;
        }

        // 删除房间并更新棋牌室房间数
        yjMahjongHallRoomService.deleteRoom(hallRoomId);
        return j;
    }

    /**
     * 绑定房间和二维码.
     * @param param
     * @return
     */
    @ApiOperation(notes = "bindQRCode", httpMethod = "PUT", value = "绑定棋牌室房间和二维码")
    @ResponseBody
    @PutMapping(value = "bindQRCode")
    public AjaxJson bindQRCode(@RequestBody Dict param) {
        AjaxJson j = new AjaxJson();

        // 检查参数
        String openId = param.getStr("openId");
        if (StringUtils.isBlank(openId)) {
            j.setSuccess(false);
            j.setMsg("用户为空");
            return j;
        }

        String salesmanPhone = param.getStr("salesmanPhone");
        if (StringUtils.isBlank(salesmanPhone)) {
            j.setSuccess(false);
            j.setMsg("业务员手机号为空");
            return j;
        }

        String roomId = param.getStr("roomId");
        if (StringUtils.isBlank(param.getStr("roomId"))) {
            j.setSuccess(false);
            j.setMsg("房间号为空");
            return j;
        }

        String qrcode = param.getStr("qrcode");
        if (StringUtils.isBlank(param.getStr("qrcode"))) {
            j.setSuccess(false);
            j.setMsg("二维码为空");
            return j;
        }

        // 检查二维码
        AjaxJson checkResult = checkQrcode(roomId, qrcode);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }

        // 开始保存绑定
        YjMahjongHallRoom room = new YjMahjongHallRoom();
        room.setId(roomId);
        room.setOpenid(openId);
        room.setSalesmanPhone(salesmanPhone);

        LinkedHashMap<String, Object> map = checkResult.getBody();
        if (map != null && map.containsKey(ROOM_KEY)) {
            YjQrcodes yjQrcodes = new YjQrcodes((String)map.get(ROOM_KEY));
            room.setQrcodes(yjQrcodes);
        }
        yjMahjongHallRoomService.saveHallRoom(room);

        j.setSuccess(true);
        j.setMsg("绑定二维码成功！");
        return j;
    }

    /**
     * 检查二维码
     * @param qrcode 二维码
     * @return
     */
    private AjaxJson checkQrcode(String qrcode) {
        AjaxJson j = new AjaxJson();

        // 检查二维码是否存在
        YjQrcodes paramQrcodes = new YjQrcodes();
        paramQrcodes.setQrcode(qrcode);
        paramQrcodes.setCategory(1);
        List<YjQrcodes> qrcodesList = yjQrcodesService.findList(paramQrcodes);
        if (qrcodesList.isEmpty())
        {
            j.setSuccess(false);
            j.setMsg("二维码不存在！");
            return j;
        }

        // 检查二维码是否已经被绑定
        YjMahjongHallRoom room = new YjMahjongHallRoom();
        YjQrcodes qrcodes = new YjQrcodes();
        qrcodes.setId(qrcodesList.get(0).getId());
        room.setQrcodes(qrcodes);
        List<YjMahjongHallRoom> roomsList = yjMahjongHallRoomService.findList(room);
        if (!roomsList.isEmpty()) {
            j.setSuccess(false);
            j.setMsg("该二维码已被绑定！");
            return j;
        }

        j.setSuccess(true);

        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put(ROOM_KEY, qrcodesList.get(0).getId());
        j.setBody(map);
        return j;
    }

    /**
     * 检查二维码
     * @param roomId 房间id
     * @param qrcode 二维码
     * @return
     */
    private AjaxJson checkQrcode(String roomId, String qrcode) {
        AjaxJson j = new AjaxJson();

        // 检查二维码是否存在
        YjQrcodes paramQrcodes = new YjQrcodes();
        paramQrcodes.setQrcode(qrcode);
        paramQrcodes.setCategory(1);
        List<YjQrcodes> qrcodesList = yjQrcodesService.findList(paramQrcodes);
        if (qrcodesList.isEmpty())
        {
            j.setSuccess(false);
            j.setMsg("二维码不存在！");
            return j;
        }

        // 检查二维码是否已经被绑定
        YjMahjongHallRoom room = new YjMahjongHallRoom();
        room.setId(roomId);
        room.setQrcodes(qrcodesList.get(0));
        boolean isDuplicate = yjMahjongHallRoomService.checkQrcodeIsDuplicate(room);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("该二维码已被绑定！");
            return j;
        }

        j.setSuccess(true);

        LinkedHashMap<String, Object> qrcodeMap = new LinkedHashMap<>();
        qrcodeMap.put(ROOM_KEY, qrcodesList.get(0).getId());
        j.setBody(qrcodeMap);
        return j;
    }

    /**
     * 重复性检查 根据名称和手机来检查是否已经创建过了
     * @param yjMahjongHallRoom
     * @return
     */
    private boolean checkDuplicate(YjMahjongHallRoom yjMahjongHallRoom) {
        YjMahjongHallRoom record = new YjMahjongHallRoom(yjMahjongHallRoom.getName(), yjMahjongHallRoom.getMahjongHall().getId());

        if (StringUtils.isNotBlank(yjMahjongHallRoom.getId())) {
            record.setId(yjMahjongHallRoom.getId());
        }

        return yjMahjongHallRoomService.isDuplicate(record);
    }
}
